﻿/*
 Json数据格式如下：

{"dataSet":{
"header":{
    "returnCode":"0",
    "errorInfo":"HTTP请求错误",
    "version":"V1.0R010",
    "totalRows":"2000",
    "returnRows":"20"
},
"fieldDefine":{
    "assetId":"string",
    "serverIdcId":"int",
    "inputTime":"datetime"
},
"data":{"row":[
{
    "AssetId":"TCNS2006888",
    "ServerIdcId":"1",
    "InputTime":"2008-12-12"
},
{
    "AssetId":"TCNS2006889",
    "ServerIdcId":"2",
    "InputTime":"2008-1-1"
}
]}
}
}

使用方法：


          GeneralSearchResult gsr = new GeneralSearchResult();  

          gsr = GeneralSearchResult.GetTransformData(text);

*/








using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Script.Serialization;


public class gtJsonTo
    {

        public Header header = new Header();

        private DataTable fieldDefine = new DataTable();

        /// <summary>

        /// 返回的数据结构定义，无数据

        /// </summary>

        public DataTable FieldDefine
        {

            get { return fieldDefine; }

            set { fieldDefine = value; }

        }


        private DataTable retrunData = new DataTable();

        /// <summary>

        /// 返回的数据，格式为DataTable，结构和FieldDefine中的结构一样

        /// </summary>

        public DataTable RetrunData
        {

            get { return retrunData; }

            set { retrunData = value; }

        }
        /// <summary>

        /// 根据DataTable得到json

        /// </summary>

        /// <param name="jsonText"></param>

        /// <returns></returns>

        public static string GetJsonFromData(DataTable dt)
        {
            string strRet = "";
            if (dt != null)
            {
                Header oHeader = new Header();
                oHeader.ErrorInfo = "";
                oHeader.ReturnCode = "0";
                oHeader.Version = "V1.0";
                oHeader.TotalRows = dt.Rows.Count;
                oHeader.ReturnRows = dt.Rows.Count;
                string strHeadjson = oHeader.strJson;

                string strFieldjson = @"""fieldDefine"":{";
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if (i == 0)
                        strFieldjson += "\"" + dt.Columns[i].ColumnName + "\":\"" + dt.Columns[i].DataType.ToString() + "\"";
                    else
                        strFieldjson += ",\"" + dt.Columns[i].ColumnName + "\":\"" + dt.Columns[i].DataType.ToString() + "\"";
                }
                strFieldjson = strFieldjson + "}";

                string strDatajson = @"""data"":{""row"":[";
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string strRowjson = "";
                    if (i != 0)
                        strRowjson += ",";
                    strRowjson = @"{";
                    for (int r = 0; r < dt.Columns.Count; i++)
                    {
                        if (r == 0)
                            strRowjson += "\"" + dt.Columns[r].ColumnName + "\":\"" + dt.Rows[i][dt.Columns[r].ColumnName].ToString().Replace("\"","\\\"") + "\"";
                        else
                            strRowjson += ",\"" + dt.Columns[r].ColumnName + "\":\"" + dt.Rows[i][dt.Columns[r].ColumnName].ToString().Replace("\"", "\\\"") + "\"";
                    }
                    strRowjson += "}";
                    strDatajson += strRowjson;
                }
                strDatajson = strDatajson + @"]}";
                strRet = "{\"dataSet\":{" + strHeadjson + "," + strFieldjson + "," + strDatajson + "}}";
            }
            return strRet;
        }

        /*{"dataSet":{
"header":{
    "returnCode":"0",
    "errorInfo":"HTTP请求错误",
    "version":"V1.0R010",
    "totalRows":"2000",
    "returnRows":"20"
},
"fieldDefine":{
    "assetId":"string",
    "serverIdcId":"int",
    "inputTime":"datetime"
},
"data":{"row":[
{
    "AssetId":"TCNS2006888",
    "ServerIdcId":"1",
    "InputTime":"2008-12-12"
},
{
    "AssetId":"TCNS2006889",
    "ServerIdcId":"2",
    "InputTime":"2008-1-1"
}
]}
}
}*/
        public static msBsc.AppLogic.Cfg.SynDictionary GetHashData(string jsonText)
        {
            msBsc.AppLogic.Cfg.SynDictionary htret = new msBsc.AppLogic.Cfg.SynDictionary(false);
            if (!string.IsNullOrEmpty(jsonText))
            {
                JavaScriptSerializer s = new JavaScriptSerializer();

                Dictionary<string, object> JsonData = (Dictionary<string, object>)s.DeserializeObject(jsonText);

                foreach (KeyValuePair<string, object> sss in JsonData)
                {

                    htret[sss.Key] = HttpContext.Current.Server.UrlDecode(sss.Value.ToString());

                }
            }
            return htret;
        }
        /// <summary>

        /// 将json数据转换为定义好的对象，数据转换为DataTable

        /// </summary>

        /// <param name="jsonText"></param>

        /// <returns></returns>

        public static gtJsonTo GetTransformData(string jsonText)
        {

            gtJsonTo gsr = new gtJsonTo();


            JavaScriptSerializer s = new JavaScriptSerializer();

            Dictionary<string, object> JsonData = (Dictionary<string, object>)s.DeserializeObject(jsonText);

            Dictionary<string, object> dataSet = (Dictionary<string, object>)JsonData["dataSet"];

            Dictionary<string, object> header = (Dictionary<string, object>)dataSet["header"];

            Dictionary<string, object> fieldDefine = (Dictionary<string, object>)dataSet["header"];

            Dictionary<string, object> data = (Dictionary<string, object>)dataSet["data"];

            object[] rows = (object[])data["row"];

            gsr.header.Version = header["version"].ToString();

            gsr.header.ErrorInfo = header["errorInfo"].ToString();

            gsr.header.ReturnCode = header["returnCode"].ToString();

            gsr.header.ReturnRows = Convert.ToInt16(header["returnRows"]);

            gsr.header.TotalRows = Convert.ToInt16(header["totalRows"]);


            Dictionary<string, object> dicFieldDefine = (Dictionary<string, object>)dataSet["fieldDefine"];

            foreach (KeyValuePair<string, object> ss in dicFieldDefine)
            {


                gsr.FieldDefine.Columns.Add(ss.Key, typeof(string));


            }

            gsr.RetrunData = gsr.FieldDefine.Clone();

            foreach (object ob in rows)
            {

                Dictionary<string, object> val = (Dictionary<string, object>)ob;

                DataRow dr = gsr.RetrunData.NewRow();

                foreach (KeyValuePair<string, object> sss in val)
                {

                    dr[sss.Key] = sss.Value;

                }

                gsr.RetrunData.Rows.Add(dr);

            }

            return gsr;

        }

        /// <summary>

        /// 数据文件头定义

        /// </summary>

        public class Header
        {

            private string version = "V1.0";

            /// <summary>

            /// 版本

            /// </summary>

            public string Version
            {

                get { return version; }

                set { version = value; }

            }

            private string returnCode="0";

            /// <summary>

            /// 结果码，0为正常，否则为有错误

            /// </summary>

            public string ReturnCode
            {

                get { return returnCode; }

                set { returnCode = value; }

            }

            private string errorInfo="";

            /// <summary>

            /// 如果ReturnCode为非0时的错误信息

            /// </summary>

            public string ErrorInfo
            {

                get { return errorInfo; }

                set { errorInfo = value; }

            }

            private int totalRows=0;

            /// <summary>

            /// 查询结果总行数

            /// </summary>

            public int TotalRows
            {

                get { return totalRows; }

                set { totalRows = value; }

            }

            private int returnRows=0;

            /// <summary>

            /// 返回的数据行数

            /// </summary>

            public int ReturnRows
            {

                get { return returnRows; }

                set { returnRows = value; }

            }

            public string strJson
            {
                get
                {
                    string strRet = "";
                    strRet = string.Format(@"""header"":{
    ""returnCode"":""{0}"",
    ""errorInfo"":""{1}"",
    ""version"":""{2}"",
    ""totalRows"":""{3}"",
    ""returnRows"":""{4}""
}", returnCode, errorInfo, version, totalRows, returnRows);
                    return strRet;
                }
            }

        }

    }

 